package com.sky.wsp.guo.mi.config;

import com.sky.wsp.guo.mi.utils.SM3PasswordEncoder;
import com.sky.wsp.guo.mi.utils.SM4PasswordEncoder;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationEventPublisher;
import org.springframework.security.authentication.DefaultAuthenticationEventPublisher;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
// @EnableWebSecurity: 启用SpringSecurity
@EnableWebSecurity
// @EnableMethodSecurity: 启用方法注解鉴权
@EnableMethodSecurity
public class SecurityConfig {
 
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                .authorizeHttpRequests(auth -> auth
                        .requestMatchers("/", "/index").permitAll()  // 公开访问
                        .anyRequest().authenticated()  // 其他接口需认证
                )
                .formLogin(Customizer.withDefaults())
                .httpBasic(Customizer.withDefaults());  // 使用 HTTP Basic 认证
        return http.build();
    }
    @Bean
    UserDetailsService inMemoryUserDetailsManager(PasswordEncoder passwordEncoder) {
        String generatedPassword = passwordEncoder.encode("123456");
        return new InMemoryUserDetailsManager(
                User.withUsername("admin")
                .password(generatedPassword).roles("ADMIN").build(),
                User.withUsername("user")
                .password(generatedPassword).roles("USER").build()
        );
    }

    @Bean
    PasswordEncoder passwordEncoder() {
//        return new SM3PasswordEncoder();
        return new SM4PasswordEncoder();
    }
}